import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:news_flutter/models/hot_search_key_model.dart';
import 'package:news_flutter/models/news_model.dart';
import 'package:news_flutter/utils/http_request_util.dart';
import 'package:news_flutter/utils/my_navigator.dart';
import 'package:news_flutter/utils/precompile.dart';
import 'package:news_flutter/utils/shared_preferences_util.dart';
import 'package:news_flutter/widgets/custom/my_appbar_widget.dart';
import 'package:news_flutter/widgets/custom/my_diver_widget.dart';
import 'package:news_flutter/widgets/custom/refresh_tableview_widget.dart';
import 'package:news_flutter/widgets/news/hot_search_item_widget.dart';
import 'package:news_flutter/widgets/news/news_items_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SearchNewsListPage extends StatefulWidget {
  @override
  _SearchNewsListPageState createState() => _SearchNewsListPageState();
}

class _SearchNewsListPageState extends State<SearchNewsListPage> {
  TextEditingController _textController;
  List<String> _searchHistoryKeys = [];
  List<HotSearchKeyModel> _hotKeys = [];
  List<NewsModel> _resluts = [];
  int _page = 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _loadHotSearchKeys();
    _textController = new TextEditingController();
    MySharedPreferences.getSearchKeyHistoryList().then((value){
      if (value!=null&&value.length>0){
        setState(() {
          _searchHistoryKeys = value;
        });
      }
    });

  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark,
      child: Scaffold(
        body: SafeArea(
            child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: _body(),
        )),
      ),
    );
  }

  //search ui
  Widget _body() {
    if (_textController.text==null||_textController.text ==""){
      return SingleChildScrollView(
        child: Column(
          children: [
            _searchBarWidget(),
            _searchKeyHistoryWidget(),
            _hotSearchKeyListWidget(),
          ],
        ),
      );
    }
    else{
      return Column(
        children: [
          _searchBarWidget(),
          Expanded(
            child: _searchResultsUI(),
          ),
        ],
      );
    }

  }

  //search bar
  Widget _searchBarWidget() {
    return Container(
      child: Row(
        children: <Widget>[
          Expanded(
            //搜索框
            child: Container(
              height: 34,
              margin: EdgeInsets.only(left: 15),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(17)),
                border: Border.all(color: MyColor.DIVER_LINE_GRAY),
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  //放大镜
                  Container(
                    margin: EdgeInsets.only(left: 5, right: 5),
                    child: Icon(
                      Icons.search,
                      color: MyColor.SUBTEXT_GRAY,
                    ),
                  ),
                  //热门关键词
                  Expanded(
                      child: TextField(
                    controller: _textController,
                    onChanged: (input) {
                      if (input ==null||input ==""){
                        setState(() {
                        });
                      }
                    },
                    onSubmitted: (input) {
                      setState(() {
                      });
                      _goSearch();
                    },
                    textInputAction: TextInputAction.search,
                    decoration: InputDecoration(
                        contentPadding: EdgeInsets.all(0.0),
                        hintText: "搜索",
                        border: OutlineInputBorder(borderSide: BorderSide.none),
                        suffixIcon: Container(
                          width: 15,
                          height: 15,
                          child: IconButton(
                            icon: Icon(
                              Icons.cancel,
                              color: MyColor.SUBTEXT_GRAY,
                            ),
                            onPressed: () {
                              _textController.clear();
                              setState(() {
                              });
                            },
                            iconSize: 18,
                          ),
                        )),
                  )),
                ],
              ),
            ),
          ),
          Container(
            width: 64,
            height: 44,
            child: FlatButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text(
                "取消",
                style: TextStyle(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  //搜索历史
  Widget _searchKeyHistoryWidget() {
    List<Widget> children = _searchHistoryKeys.map((e) {
      return OutlineButton(
        highlightedBorderColor: Colors.transparent,
        onPressed: () {
          _textController.text =e;
          _goSearch();
        },
        child: Text(
          e,
        ),
      );
    }).toList();
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                "搜索历史",
                style: TextStyle(color: MyColor.SUBTEXT_GRAY, fontSize: 15),
              ),
              //删除按钮
              InkWell(
                onTap: () {
                  _clearSearchHistoryKeys();
                },
                child: Container(
                  width: 34,
                  height: 34,
                  child: Icon(Icons.delete, color: MyColor.SUBTEXT_GRAY),
                ),
              ),
            ],
          ),
          Container(
            child: Wrap(
              children: children,
              spacing: 10,
              runSpacing: 1,
            ),
          ),
        ],
      ),
    );
  }

  //热搜榜单
  Widget _hotSearchKeyListWidget() {
    List<Widget> children = _hotKeys.map((HotSearchKeyModel model) {
      return HotSearchItem(
        model: model,
        index: _hotKeys.indexOf(model),
        tapCallback: (tapModel) {
          _textController.text =tapModel.word;
          _goSearch();
        },
      );
    }).toList();
    return Column(
      children: <Widget>[
        //Divefr
        MyDiver(),
        //title
        Container(
          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
          child: Row(
            children: <Widget>[
              Container(
                width: 92,
                height: 17,
                margin: EdgeInsets.only(right: 5),
                child: Image(
                  image: AssetImage("assets/images/hot_search_tag.png"),
                ),
              ),
              Container(
                child: Text("每30分钟更新"),
              ),
            ],
          ),
        ),
        MyDiver(),
        Column(
          children: children,
        ),
      ],
    );
  }

  //获取热搜列表
  void _loadHotSearchKeys() {
    HttpRequestUtil().get("txapi/douyinhot/index", param: {}).then((value) {
      List newslist = value["newslist"];
      List<HotSearchKeyModel> list =
          newslist.map((e) => HotSearchKeyModel.fromJsonMap(e)).toList();
      setState(() {
        _hotKeys = list;
      });
    });
  }

  //search result ui
  Widget _searchResultsUI() {
    return RefreshTableView(
      onRefresh: () {
        _loadData(isRefresh: true);
      },
      onLoadMore: () {
        _loadData();
      },
      itemBuilder: (BuildContext context, int index) {
        return NewsItemWidget(
          newsModel: _resluts[index],
        );
      },
      itemCount: _resluts.length,
    );
  }
  //clear search
  void _clearSearchHistoryKeys(){
    MySharedPreferences.setSearchKeyHistoryList([]);
    setState(() {
      _searchHistoryKeys =[];
    });
  }

  void _goSearch() {
    if (_textController.text!=null&&_textController.text!=""){
      if (_searchHistoryKeys.contains(_textController.text)) {
        _searchHistoryKeys.remove(_textController.text);
      }
      _searchHistoryKeys.insert(0, _textController.text);
      int maxCount = 5;
      if (_searchHistoryKeys.length > maxCount) {
        _searchHistoryKeys.removeRange(
            maxCount - 1, _searchHistoryKeys.length - 1);
      }
      MySharedPreferences.setSearchKeyHistoryList(_searchHistoryKeys);
    }
    _loadData(isRefresh: true);
  }

  //加载数据
  void _loadData({bool isRefresh = false}) {
    if (isRefresh == true) {
      _page = 1;
    } else {
      _page++;
    }
    HttpRequestUtil().get("topnews/index",
        param: {"page": _page, "num": 20, "word": "${_textController.text}"}).then((value) {
      List newslist = value["newslist"];
      List<NewsModel> list =[];
      if (newslist!=null&&newslist is List){
        list = newslist.map((e) => NewsModel.fromJsonMap(e)).toList();
      }
      if (isRefresh == true) {
        _resluts = list;
      } else {
        _resluts = _resluts + list;
      }
      setState(() {});
    });
  }
}
